import { setAnimateStyle } from './setAnimateStyle'
import { setMarkerStyle } from './setStyle'
// import { setPntStyle } from './setStyle'
import {
  DrawSource,
  DrawLayer,
  BoxDrawLayer,
  BoxDrawSource,
  MeasuringLayer,
  MeasuringSource,
  EventLayer,
  EventSource,
  HighlightLayer
} from '@/plugins/Layers'
import { setPoint, resetPoint } from '@/request/axios'
// 导出图片功能
function exportImg(map) {
  map.once('postcompose', function (event) {
    const canvas = event.context.canvas
    // canvas能正常获取
    console.log(canvas, 'canvas')
    // toBlob方法是自带的。报错 Failed to execute 'toBlob' on 'HTMLCanvasElement': Tainted canvases may not be exported.
    canvas.toBlob(function (blob) {
      console.log(blob)
      //  saveAs方法是单独导入的
      saveAs(blob, 'map.png')
    })
  })
  map.renderSync()
}

// 画笔添功能
/**
 * @param {String} type ="Box"|"Square"|"Point"
 * 可以理解为正方形是圆衍生出来的，而长方形是线衍生出来的
 * */
function createDraw({ source, type }) {
  let geometryFunction = null
  let maxPoints = null
  if (type == 'Box') {
    type = 'LineString'
    geometryFunction = function (coordinates, geometry) {
      if (!geometry) {
        //多边形
        geometry = new ol.geom.Polygon(null)
      }
      var start = coordinates[0]
      var end = coordinates[1]
      geometry.setCoordinates([[start, [start[0], end[1]], end, [end[0], start[1]], start]])
      return geometry
    }
    maxPoints = 2
  } else if (type == 'Square') {
    type = 'Circle'
    geometryFunction = ol.interaction.Draw.createRegularPolygon(4)
  }
  let draw = new ol.interaction.Draw({
    // 在哪个画布上绘制
    source: source,
    type,
    geometryFunction,
    maxPoints
  })
  return draw
}

// 添加弹窗
function createPopuo(map, container, content, closer, position, ctx) {
  const timestamp = Date.now()
  const popup = new ol.Overlay({
    id: timestamp,
    //要转换成overlay的HTML元素
    element: container,
    //当前窗口可见
    autoPan: true,
    //Popup放置的位置
    positioning: 'bottom-center',
    //是否应该停止事件传播到地图窗口
    stopEvent: true,
    autoPanAnimation: {
      //当Popup超出地图边界时，为了Popup全部可见，地图移动的速度
      duration: 250
    }
  })
  map.addOverlay(popup)
  /* 4、对地图监听,点击到对应要素popup弹窗显示（设置坐标和 */
  //为map添加鼠标移动事件监听,当鼠标移动到元素上的时候会显示手型
  map.on('pointermove', function (e) {
    var pixel = map.getEventPixel(e.originalEvent)
    var hit = map.hasFeatureAtPixel(pixel)
    map.getTargetElement().style.cursor = hit ? 'pointer' : ''
  })
  // console.log(content,'ctx');
  content.innerHTML = ctx
  // console.log(position,ctx,'positon,ctx');
  popup.setPosition(position)
  // container.style.visibility = 'visible'
  //添加关闭按钮的单击事件（隐藏popup）
  closer.onclick = function () {
    //未定义popup位置
    popup.setPosition(undefined)
    //失去焦点
    closer.blur()
    return false
  }
}

//添加兴趣点
function addInterestPoint(map) {
  let src = '/五角星.png'
  DrawLayer.setStyle(setMarkerStyle(src))
  // 创建画笔
  let draw = createDraw({
    type: 'Point',
    source: DrawSource
  })
  //  激活画笔
  map.addInteraction(draw)

  // 画笔事件
  draw.on('drawend', (evt) => {
    // 将点包装成单点 geojson 数据格式
    let center = evt.feature.getGeometry().getCoordinates()
    let interestPoint = {
      type: 'Feature',
      geometry: {
        type: 'Point',
        coordinates: center
      }
    }

    // 拿到本地存储的账户信息
    const localInfo = JSON.parse(localStorage.getItem('account'))
    const { username, password, type } = localInfo
    // 发送post请求，
    setPoint(username, password, type, interestPoint)

    /* 移除画笔 */
    map.removeInteraction(draw)
  })
}
//添加事件点
function addEventPoint(map) {
  return new Promise((resolve, reject) => {
    let coordinate
    let pixel
    let src = '/像素_旗帜.png'
    EventLayer.setStyle(setMarkerStyle(src))
    // 创建画笔
    let draw = createDraw({
      type: 'Point',
      source: EventSource
    })
    // 激活画笔
    map.addInteraction(draw)
    // 画笔事件
    draw.on('drawend', (evt) => {
      try {
        // 将点包装成单点 geojson 数据格式
        coordinate = evt.feature.getGeometry().getCoordinates()
        // 转换为屏幕坐标
        pixel = map.getPixelFromCoordinate(coordinate)

        /* 移除画笔 */
        map.removeInteraction(draw)

        // 解析成功时返回坐标和像素
        resolve({ coordinate, pixel })
      } catch (error) {
        // 解析过程中出错时返回错误
        reject(error)
      }
    })

    // 可选：设置一个超时，避免永远等待
    setTimeout(() => {
      map.removeInteraction(draw)
      reject(new Error('绘制超时'))
    }, 10000) // 10秒超时
  })
}

// 拉框删除
function clearInterestPoint(map) {
  // 给矩形图层设置点样式，就不会渲染矩形
  BoxDrawLayer.setStyle(setAnimateStyle({ map }))
  // 创建画笔
  let draw = createDraw({
    type: 'Box',
    source: BoxDrawSource
  })
  //  激活画笔
  map.addInteraction(draw)
  // 画笔事件
  draw.on('drawend', (evt) => {
    // 拿到 draw 对象
    let feature = evt.feature
    /* feature-geojson */
    let polygon = new ol.format.GeoJSON().writeFeatureObject(feature)
    console.log(polygon, '面要素转geojson')
    /* 获取所有的DrawSource要素
    1、如果在polygon中的就删除
    2、不在的不删除
     */
    let features = DrawSource.getFeatures()
    /* 清空矩形画布 */
    BoxDrawLayer.getSource().clear()
    // 删除被选中点
    features.forEach((item) => {
      let point = new ol.format.GeoJSON().writeFeatureObject(item)
      var result = turf.booleanContains(polygon, point)
      if (result) {
        DrawSource.removeFeature(item)
      }
    })
    let resetFeatures = DrawSource.getFeatures()
    console.log(11)
    let interestPoints = new ol.format.GeoJSON().writeFeaturesObject(resetFeatures)
    // 拿到本地存储的账户信息
    const localInfo = JSON.parse(localStorage.getItem('account'))
    const { username, password, type } = localInfo
    // 发送post请求，
    resetPoint(username, password, type, interestPoints)
    /* 移除画笔 */
    map.removeInteraction(draw)
  })
}

// 拉框查询——返回一个查询到的要素
function queryEvent(map) {
  return new Promise((resolve, reject) => {
    HighlightLayer.getSource().clear()
    HighlightLayer.setStyle(setAnimateStyle({ map, size:30 }))
    // 给矩形图层设置点样式，就不会渲染矩形
    BoxDrawLayer.setStyle(setAnimateStyle({ map }))
    // 创建画笔
    let draw = createDraw({
      type: 'Box',
      source: BoxDrawSource
    })
    //  激活画笔
    map.addInteraction(draw)
    // 画笔事件
    draw.on('drawend', (evt) => {
      try {
        let geometry = evt.feature.getGeometry()
        const service = {
          name: 'guanggu3',
          layerId: [4, 5, 6]
        }
        Query.queryByGeom({
          geometry,
          service,
          success: (featuresObj) => {
            for (let key in featuresObj) {
                  if(featuresObj[key]){
                    HighlightLayer.getSource().addFeatures(featuresObj[key]);
                  }
          }
          
            // console.log(featuresObj,'看看fearures');
            // 这个数据怎么处理，全看后面表格需要什么格式的吧
            resolve(featuresObj) // 成功时返回结果
          }
        })
        /* 移除画笔 */
        map.removeInteraction(draw)
      } catch (error) {
        // 解析过程中出错时返回错误
        reject(error)
      }
      // 可选：设置一个超时，避免永远等待
      setTimeout(() => {
        map.removeInteraction(draw)
        reject(new Error('绘制超时'))
      }, 10000) // 10秒超时
    })
  })
}

// 测量距离
function MeasuringDistance(map, container, content, closer) {
  // 创建画笔
  let draw = createDraw({
    type: 'LineString',
    source: MeasuringSource
  })
  //  激活画笔
  map.addInteraction(draw)
  // 画笔事件
  draw.on('drawend', (evt) => {
    // 拿到 draw 对象
    let feature = evt.feature
    let positionArr = feature.getGeometry().getCoordinates()
    let position = positionArr[positionArr.length - 1]
    /* feature-geojson */
    let line = new ol.format.GeoJSON().writeFeatureObject(feature)
    let length = turf.length(line)
    // 将长度单位根据情况进行换算
    let ctx
    if (length >= 1) {
      let lengthKm = parseFloat(length.toFixed(3))
      ctx = `${lengthKm} 千米`
    } else {
      let lengthMeters = parseFloat((length * 1000).toFixed(0))
      ctx = `${lengthMeters} 米`
    }
    /* 清空矩形画布 */
    MeasuringLayer.getSource().clear()

    /* 移除画笔 */
    map.removeInteraction(draw)
    createPopuo(map, container, content, closer, position, ctx)
  })
}
// 测量面积
function MeasuringArea(map, container, content, closer) {
  // 创建画笔
  let draw = createDraw({
    type: 'Polygon',
    source: MeasuringSource
  })
  //  激活画笔
  map.addInteraction(draw)
  // 画笔事件
  draw.on('drawend', (evt) => {
    // 拿到 draw 对象
    let feature = evt.feature
    // 拿到绘制的最后一个点的坐标
    let positionArr = feature.getGeometry().getCoordinates()[0]
    let position = positionArr[positionArr.length - 2]
    // 将 draw 对象转为geojson格式，turf计算面积
    let polygon = new ol.format.GeoJSON().writeFeatureObject(feature)
    let area = turf.area(polygon)
    // 将面积单位根据情况进行换算
    let ctx
    if (area >= 10000) {
      let areaKM2 = parseFloat((area / 1000000).toFixed(2))
      ctx = `${areaKM2} 平方千米`
    } else {
      let areaM2 = parseFloat(area.toFixed(0))
      ctx = `${areaM2} 平方米`
    }
    /* 清空矩形画布 */
    MeasuringLayer.getSource().clear()

    /* 移除画笔 */
    map.removeInteraction(draw)
    // 创建弹窗
    createPopuo(map, container, content, closer, position, ctx)
  })
}
export {
  exportImg,
  createDraw,
  addInterestPoint,
  clearInterestPoint,
  MeasuringDistance,
  MeasuringArea,
  createPopuo,
  addEventPoint,
  queryEvent
}
